import { useDesign } from '@/hooks/useDesign';
import { pathResolve } from '@/utils/routerHelper';
import { ElMenuItem, ElSubMenu } from 'element-plus';
import { unref } from 'vue';
import { hasOneShowingChild } from '../helper';
import { useRenderMenuTitle } from './useRenderMenuTitle';

const prefixCls = useDesign().getPrefixCls('submenu');

const { renderMenuTitle } = useRenderMenuTitle();

export const useRenderMenuItem = (menuMode: 'vertical' | 'horizontal') => {
  const renderMenuItem = (routers: AppRouteRecordRaw[], parentPath = '/') => {
    return routers
      .filter((v) => !v.meta?.hidden)
      .map((v) => {
        const meta = v?.meta ?? {};
        // 判断是否只有一个子路由
        const { oneShowingChild, onlyOneChild } = hasOneShowingChild(v.children, v);
        const fullPath = pathResolve(parentPath, v.path);

        if (oneShowingChild && (!onlyOneChild?.children || onlyOneChild?.noShowingChildren) && !meta?.alwaysShow) {
          return (
            <ElMenuItem index={onlyOneChild ? pathResolve(fullPath, onlyOneChild.path) : fullPath}>
              {{ default: () => renderMenuTitle(onlyOneChild?.meta ?? meta) }}
            </ElMenuItem>
          );
        } else {
          // 有多级子路由
          return (
            <ElSubMenu index={fullPath} teleported popperClass={unref(menuMode) === 'vertical' ? `${prefixCls}-popper--vertical` : ''}>
              {{
                default: () => renderMenuItem(v.children!, fullPath),
                title: () => renderMenuTitle(meta)
              }}
            </ElSubMenu>
          );
        }
      });
  };

  return {
    renderMenuItem
  };
};
